#include "musicslider.h"
#include "ui_musicslider.h"

MusicSlider::MusicSlider(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicSlider)
{
    ui->setupUi(this);
    this->maxWidth=this->width();
    this->currentWidth=0;
    moveSlider();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::setStep(float rate)
{
    currentWidth=maxWidth*rate;
    moveSlider();
}

void MusicSlider::mousePressEvent(QMouseEvent *event)
{
    if(event->buttons()==Qt::LeftButton)
    {
        currentWidth=event->pos().x();
        moveSlider();
        emit this->musicSliderChanged(currentWidth/(float)maxWidth);
    }
}

void MusicSlider::mouseReleaseEvent(QMouseEvent *event)
{
    currentWidth=event->pos().x();
    moveSlider();
    emit this->musicSliderChanged(currentWidth/(float)maxWidth);
}

void MusicSlider::mouseMoveEvent(QMouseEvent *event)
{
    QRect rect=QRect(0,0,this->width(),this->height());
    if(!rect.contains(event->pos()))
          return ;
    if(event->buttons()==Qt::LeftButton)
    {
        currentWidth=event->pos().x();
        if(currentWidth<0)
            currentWidth=0;
        if(currentWidth>maxWidth)
            currentWidth=maxWidth;

        moveSlider();
        emit this->musicSliderChanged(currentWidth/(float)maxWidth);
    }
}

void MusicSlider::moveSlider()
{
    ui->outline->setGeometry(ui->outline->x(),ui->outline->y(),currentWidth,ui->outline->height());

}
